<template>
  <el-dialog
    v-model="dialogVisible"
    title="AI助手偏好设置"
    width="600px"
    :before-close="handleClose"
  >
    <div class="preferences-content">
      <el-form 
        ref="formRef"
        :model="preferences" 
        :rules="rules"
        label-width="120px"
        label-position="left"
      >
        <!-- 基本设置 -->
        <div class="section">
          <h3 class="section-title">
            <el-icon><User /></el-icon>
            基本设置
          </h3>
          
          <el-form-item label="技能水平" prop="skillLevel">
            <el-select v-model="preferences.skillLevel" style="width: 100%">
              <el-option label="初学者" value="BEGINNER">
                <div class="skill-option">
                  <span class="skill-name">初学者</span>
                  <span class="skill-desc">刚开始学习编程，需要详细的基础解释</span>
                </div>
              </el-option>
              <el-option label="中级" value="INTERMEDIATE">
                <div class="skill-option">
                  <span class="skill-name">中级</span>
                  <span class="skill-desc">有一定基础，可以理解复杂概念</span>
                </div>
              </el-option>
              <el-option label="高级" value="ADVANCED">
                <div class="skill-option">
                  <span class="skill-name">高级</span>
                  <span class="skill-desc">经验丰富，关注最佳实践和高级技巧</span>
                </div>
              </el-option>
              <el-option label="专家" value="EXPERT">
                <div class="skill-option">
                  <span class="skill-name">专家</span>
                  <span class="skill-desc">可以讨论深层原理和架构设计</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="主要语言" prop="currentLanguage">
            <el-select v-model="preferences.currentLanguage" style="width: 100%" clearable>
              <el-option label="Java" value="Java" />
              <el-option label="Python" value="Python" />
              <el-option label="JavaScript" value="JavaScript" />
              <el-option label="TypeScript" value="TypeScript" />
              <el-option label="C++" value="C++" />
              <el-option label="Go" value="Go" />
              <el-option label="Rust" value="Rust" />
              <el-option label="PHP" value="PHP" />
              <el-option label="C#" value="C#" />
              <el-option label="Swift" value="Swift" />
              <el-option label="Kotlin" value="Kotlin" />
              <el-option label="其他" value="Other" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="学习目标" prop="learningGoals">
            <el-input
              v-model="preferences.learningGoals"
              type="textarea"
              :rows="3"
              placeholder="描述你的学习目标，例如：掌握Spring Boot开发、准备技术面试、学习算法等"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </div>
        
        <!-- AI交互设置 -->
        <div class="section">
          <h3 class="section-title">
            <el-icon><ChatDotRound /></el-icon>
            AI交互设置
          </h3>
          
          <el-form-item label="解释风格">
            <el-radio-group v-model="preferences.explanationStyle">
              <el-radio label="详细">详细解释，包含背景知识</el-radio>
              <el-radio label="简洁">简洁明了，直接给出要点</el-radio>
              <el-radio label="实例导向">通过实际例子来解释概念</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="代码示例">
            <el-switch
              v-model="preferences.codeExamples"
              active-text="总是提供代码示例"
              inactive-text="仅在必要时提供示例"
            />
          </el-form-item>
          
          <el-form-item label="交互模式">
            <el-switch
              v-model="preferences.interactiveMode"
              active-text="启用互动式学习"
              inactive-text="直接给出答案"
            />
          </el-form-item>
          
          <el-form-item label="难度偏好">
            <el-select v-model="preferences.difficultyPreference" style="width: 100%">
              <el-option label="渐进式" value="渐进式">
                <span>从简单到复杂，循序渐进</span>
              </el-option>
              <el-option label="挑战性" value="挑战性">
                <span>提供有挑战性的内容</span>
              </el-option>
              <el-option label="实用性" value="实用性">
                <span>专注于实际应用场景</span>
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="反馈频率">
            <el-select v-model="preferences.feedbackFrequency" style="width: 100%">
              <el-option label="实时" value="实时">
                <span>立即指出问题和建议</span>
              </el-option>
              <el-option label="阶段性" value="阶段性">
                <span>在完成一个话题后给出反馈</span>
              </el-option>
              <el-option label="总结性" value="总结性">
                <span>在会话结束时提供总结</span>
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        
        <!-- 学习偏好 -->
        <div class="section">
          <h3 class="section-title">
            <el-icon><Reading /></el-icon>
            学习偏好
          </h3>
          
          <el-form-item label="关注领域">
            <el-checkbox-group v-model="preferences.focusAreas">
              <el-checkbox label="算法与数据结构">算法与数据结构</el-checkbox>
              <el-checkbox label="Web开发">Web开发</el-checkbox>
              <el-checkbox label="移动开发">移动开发</el-checkbox>
              <el-checkbox label="后端开发">后端开发</el-checkbox>
              <el-checkbox label="前端开发">前端开发</el-checkbox>
              <el-checkbox label="数据库">数据库</el-checkbox>
              <el-checkbox label="系统设计">系统设计</el-checkbox>
              <el-checkbox label="DevOps">DevOps</el-checkbox>
              <el-checkbox label="机器学习">机器学习</el-checkbox>
              <el-checkbox label="网络安全">网络安全</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          
          <el-form-item label="学习方式">
            <el-checkbox-group v-model="preferences.learningMethods">
              <el-checkbox label="理论学习">理论概念学习</el-checkbox>
              <el-checkbox label="实践项目">动手实践项目</el-checkbox>
              <el-checkbox label="代码审查">代码审查与重构</el-checkbox>
              <el-checkbox label="问题解决">问题解决训练</el-checkbox>
              <el-checkbox label="最佳实践">最佳实践分享</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
        
        <!-- 通知设置 -->
        <div class="section">
          <h3 class="section-title">
            <el-icon><Bell /></el-icon>
            通知设置
          </h3>
          
          <el-form-item label="学习提醒">
            <el-switch
              v-model="preferences.learningReminders"
              active-text="开启学习提醒"
              inactive-text="关闭学习提醒"
            />
          </el-form-item>
          
          <el-form-item label="进度通知">
            <el-switch
              v-model="preferences.progressNotifications"
              active-text="接收学习进度通知"
              inactive-text="不接收进度通知"
            />
          </el-form-item>
          
          <el-form-item label="新功能通知">
            <el-switch
              v-model="preferences.featureUpdates"
              active-text="接收新功能通知"
              inactive-text="不接收功能更新"
            />
          </el-form-item>
        </div>
      </el-form>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button @click="resetToDefaults">恢复默认</el-button>
        <el-button type="primary" @click="savePreferences" :loading="saving">
          保存设置
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage, type FormInstance } from 'element-plus'
import { User, ChatDotRound, Reading, Bell } from '@element-plus/icons-vue'
import { enhancedAIApi } from '@/api/enhanced-ai'

interface Props {
  modelValue: boolean
}

interface UserPreferences {
  skillLevel: string
  currentLanguage: string
  learningGoals: string
  explanationStyle: string
  codeExamples: boolean
  interactiveMode: boolean
  difficultyPreference: string
  feedbackFrequency: string
  focusAreas: string[]
  learningMethods: string[]
  learningReminders: boolean
  progressNotifications: boolean
  featureUpdates: boolean
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'updated': [preferences: UserPreferences]
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const saving = ref(false)

const preferences = ref<UserPreferences>({
  skillLevel: 'BEGINNER',
  currentLanguage: '',
  learningGoals: '',
  explanationStyle: '详细',
  codeExamples: true,
  interactiveMode: true,
  difficultyPreference: '渐进式',
  feedbackFrequency: '实时',
  focusAreas: [],
  learningMethods: [],
  learningReminders: true,
  progressNotifications: true,
  featureUpdates: true
})

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 表单验证规则
const rules = {
  skillLevel: [
    { required: true, message: '请选择技能水平', trigger: 'change' }
  ],
  learningGoals: [
    { max: 500, message: '学习目标不能超过500个字符', trigger: 'blur' }
  ]
}

// 默认设置
const defaultPreferences: UserPreferences = {
  skillLevel: 'BEGINNER',
  currentLanguage: '',
  learningGoals: '',
  explanationStyle: '详细',
  codeExamples: true,
  interactiveMode: true,
  difficultyPreference: '渐进式',
  feedbackFrequency: '实时',
  focusAreas: [],
  learningMethods: [],
  learningReminders: true,
  progressNotifications: true,
  featureUpdates: true
}

// 方法
const loadPreferences = async () => {
  try {
    const stats = await enhancedAIApi.getUserStats()
    
    // 从用户统计中加载基本信息
    preferences.value.skillLevel = stats.skillLevel || 'BEGINNER'
    preferences.value.currentLanguage = stats.currentLanguage || ''
    
    // 从本地存储加载其他偏好设置
    const savedPreferences = localStorage.getItem('ai-preferences')
    if (savedPreferences) {
      const parsed = JSON.parse(savedPreferences)
      preferences.value = { ...preferences.value, ...parsed }
    }
  } catch (error) {
    console.error('加载偏好设置失败:', error)
  }
}

const savePreferences = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    saving.value = true
    
    // 保存到后端
    await enhancedAIApi.updateUserPreferences({
      currentLanguage: preferences.value.currentLanguage,
      learningGoals: preferences.value.learningGoals
    })
    
    // 保存到本地存储
    localStorage.setItem('ai-preferences', JSON.stringify(preferences.value))
    
    ElMessage.success('偏好设置保存成功')
    emit('updated', preferences.value)
    dialogVisible.value = false
  } catch (error: any) {
    ElMessage.error('保存失败：' + (error.message || '未知错误'))
  } finally {
    saving.value = false
  }
}

const resetToDefaults = () => {
  preferences.value = { ...defaultPreferences }
  ElMessage.info('已恢复默认设置')
}

const handleClose = () => {
  dialogVisible.value = false
}

// 监听对话框打开
watch(dialogVisible, (visible) => {
  if (visible) {
    loadPreferences()
  }
})

// 组件挂载时加载偏好设置
onMounted(() => {
  loadPreferences()
})
</script>

<style scoped>
.preferences-content {
  max-height: 600px;
  overflow-y: auto;
}

.section {
  margin-bottom: 32px;
}

.section:last-child {
  margin-bottom: 16px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  padding-bottom: 8px;
  border-bottom: 2px solid #f0f0f0;
}

.skill-option {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.skill-name {
  font-weight: 500;
  color: #303133;
}

.skill-desc {
  font-size: 12px;
  color: #909399;
}

/* 表单样式调整 */
:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-textarea__inner) {
  resize: none;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.el-checkbox) {
  margin-right: 0;
  height: auto;
}

:deep(.el-checkbox__label) {
  padding-left: 8px;
  line-height: 1.4;
}

:deep(.el-radio-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.el-radio) {
  margin-right: 0;
  height: auto;
}

:deep(.el-radio__label) {
  padding-left: 8px;
  line-height: 1.4;
}

:deep(.el-switch) {
  height: auto;
}

:deep(.el-switch__label) {
  font-size: 14px;
  color: #606266;
}

/* 对话框底部 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 滚动条样式 */
.preferences-content::-webkit-scrollbar {
  width: 6px;
}

.preferences-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.preferences-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.preferences-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }
  
  .preferences-content {
    max-height: 70vh;
  }
  
  :deep(.el-form--label-left .el-form-item__label) {
    text-align: left;
    width: 100px !important;
  }
  
  :deep(.el-checkbox-group),
  :deep(.el-radio-group) {
    margin-left: 0;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .section-title {
    color: #e4e7ed;
    border-bottom-color: #4c4d4f;
  }
  
  .skill-name {
    color: #e4e7ed;
  }
  
  .skill-desc {
    color: #909399;
  }
}
</style>
